<template>
	<view>
		<my-navbar class="page-navbar" :border="false" backgroundColor="rgba(0,0,0,0)" :fns="c_navbar.fns" @handle="c_navbar.handle">
			<template v-slot:left>
				<image v-if="loginMode === 'wechat'" class="navbar-left home" src="/static/index/icon_home.png" mode="scaleToFill"></image>
				<image v-else class="navbar-left back" src="/static/img/icon_back.png" mode="scaleToFill"></image>
			</template>
		</my-navbar>
		<view class="page-background">
			<view class="background-image">
				<image class="image-top" src="/static/login/background_0.png"></image>
				<image class="image-bottom" src="/static/login/background_1.png"></image>
			</view>
		</view>
		<view class="login">
			<view class="login-logo">
				<image class="logo-icon" v-if="theme.resourcePath" :src="`${theme.resourcePath}/login/icon_logo.png`"></image>
				<view class="logo-text">
					<view class="font-type">{{ theme.name }}</view>
					<view class="circle"></view>
					<view class="font-type">老师端</view>
				</view>
			</view>
			<view v-if="loginMode === 'wechat'" class="login-index">
				<view class="index-rules">
					<view>需学校管理员将您加为老师后才能使用</view>
					<view>登录需要获取您的公开信息（昵称，头像，地区及性别等）</view>
					<view>
						<text>授权登录即代表同意</text>
						<text class="hl" @click="clickAgreement('t1')">《服务协议》</text>
						<text class="hl" @click="clickAgreement('t2')">《隐私协议》</text>
					</view>
				</view>
				<view class="index-buttons">
					<view class="app-button login-button primary" hover-class="hover" @click="loginByWechat">微信授权登录</view>
					<view class="app-button login-button" hover-class="hover" @click="selectLoginMode('sms')">手机号登录</view>
				</view>
			</view>
			<view v-else class="login-form">
				<view class="form-item" @click="i_phone.clickItem">
					<view class="item-label">手机号</view>
					<input class="item-value" v-model="i_phone.data.phone" type="text" placeholder="请输入手机号码" placeholder-style="color: #C3C3C3;" />
					<view class="item-button app-button" :class="isCanGetCode ? 'active' : 'disabled'" hover-class="hover" @click="c_code.sendCode">{{ c_code.text }}</view>
					<view class="item-error">{{ i_phone.error }}</view>
				</view>
				<view class="form-item" @click="i_code.clickItem">
					<view class="item-label">验证码</view>
					<input class="item-value" v-model="i_code.data.code" type="number" maxlength="6" placeholder="请输入验证码" placeholder-style="color: #C3C3C3;" />
					<view class="item-error">{{ i_code.error }}</view>
				</view>
				<view class="form-buttons">
					<view class="login-button app-button primary" :class="[l_isPass ? '' : 'disabled']" hover-class="hover" @click="loginBySms">登录</view>
				</view>
			</view>
		</view>
		<my-popup :custom="1" :show="p_phone.show" @handle="p_phone.handle">
			<view class="popup1">
				<view class="popup1-content">授权绑定你的手机号码</view>
				<view class="popup1-buttons">
					<view class="button-item app-button" hover-class="hover" @click="p_phone.clickButton(0)">拒绝</view>
					<button class="button-item primary app-button" hover-class="hover" open-type="getPhoneNumber" @getphonenumber="p_phone.clickButton(1, $event)">允许</button>
				</view>
			</view>
		</my-popup>
		<my-code ref="code" @handle="c_code.handle"></my-code>
	</view>
</template>

<script>
import form from '@/components/my-form/my-form.js';
import MyCode from '@/components/my-code/my-code';
import { loginEnum } from './loginEnum.js';
import { mapState, mapActions } from 'vuex';
export default {
	data() {
		return {
			i_phone: {
				data: {
					phone: ''
				},
				error: '',
				checkData: () => {
					const context = this.i_phone;
					return [
						() => {
							if (!context.data.phone) return '请输入11位手机号';
						},
						() => {
							if (!/^1[3456789]\d{9}$/.test(context.data.phone)) return '请输入正确的手机号';
						}
					];
				},
				clickItem: () => {
					const context = this.i_phone;
					context.error = '';
				}
			},
			i_code: {
				data: {
					code: ''
				},
				error: '',
				checkData: () => {
					const context = this.i_code;
					return [
						() => {
							if (!context.data.code) return '请输入验证码';
						},
						() => {
							if (context.data.code.length < 6) return '验证码错误，请重试';
						}
					];
				},
				clickItem: () => {
					const context = this.i_code;
					context.error = '';
				}
			},
			c_navbar: {
				fns: ['clickLeft'],
				handle: (fn, e, payload) => {
					if (fn === 'clickLeft') this.c_navbar.handleClickLeft();
				},
				handleClickLeft: () => {
					if (this.loginMode === 'wechat') {
						uni.reLaunch({
							url: '/pages/index/index'
						});
					} else {
						this.loginMode = 'wechat';
					}
				}
			},
			c_code: {
				text: '',
				handle: (fn, e, payload) => {
					if (fn === 'change') this.c_code.handleChange(payload);
				},
				handleChange: countdown => {
					if (countdown == 0) {
						this.c_code.text = '获取验证码';
					} else {
						this.c_code.text = `重新获取(${countdown}s)`;
					}
				},
				sendCode: async () => {
					if (this.$refs.code.wait) {
						this.$showToast('倒计时结束后再获取');
						return;
					}
					let errors = form.checkItemData(this.i_phone);
					if (errors.length) {
						let error = errors.find(i => i);
						this.$showToast(error);
						return;
					}
					let itemData = form.getItemData(this.i_phone);
					let res1;
					try {
						res1 = await this.$api.common.send_sms_code({ phone: itemData.phone, busCode: 'TEACHER_LOGIN', template: '' });
					} catch (err) {
						this.$showToast(err.message || '发送验证码失败');
						return;
					}
					this.$refs.code.start();
					this.$showToast('发送成功');
				}
			},
			// 弹窗：授权绑定你的手机号码
			p_phone: {
				show: false,
				handle: fn => {},
				clickButton: async (id, e) => {
					this.p_phone.show = false;
					if (id == 0) return;
					if (!e.detail.encryptedData) return;
					uni.showLoading({
						mask: true
					});
					let res1;
					try {
						res1 = await uni.checkSession();
						if (res1[0]) throw res1[0];
						res1 = res1[1];
					} catch (err) {
						this.getCode();
						uni.hideLoading();
						this.$showToast('登录状态已过期，请重试');
						return;
					}
					let res2;
					try {
						res2 = await this.$api.user.get_user_wx_phone_number({
							code: e.detail.code
						});
					} catch (err) {
						uni.hideLoading();
						this.$showToast(err.message || '获取手机号码失败');
						return;
					}
					uni.hideLoading();
					this.login({
						phone: res2.result.phone_info.phoneNumber
					});
				}
			},
			loginMode: 'wechat', // 登录方式
			// loginState START
			code: '', // 5 分钟更新一次的 code
			userProfile: {}, // 用户头像
			// loginState END
			codeTimer: null
		};
	},
	computed: {
		l_list() {
			return [this.i_phone, this.i_code];
		},
		l_isPass() {
			return form.checkListData(this.l_list).length === 0;
		},
		isCanGetCode() {
			return form.checkItemData(this.i_phone).length === 0 && this.c_code.text === '获取验证码';
		},
		...mapState({
			theme: state => state.Theme.theme
		})
	},
	methods: {
		...mapActions(['updateJxyUserInfo']),
		// 更新 code（持续）
		async getCode() {
			let res1;
			try {
				res1 = await uni.login();
				if (res1[0]) throw res1[0];
				res1 = res1[1];
			} catch (err) {}
			this.code = res1.code;
			if (this.codeTimer) clearInterval(this.codeTimer);
			this.codeTimer = setInterval(() => {
				this.getCode();
			}, 1000 * 60 * 4);
		},
		// 选择登录方式（微信授权登录-wechat 手机号登录-sms）
		selectLoginMode(loginMode) {
			this.loginMode = loginMode;
		},
		// 微信授权登录
		async loginByWechat() {
			if (!Object.keys(this.userProfile).length) {
				let res1;
				try {
					res1 = await uni.getUserProfile({
						desc: '用于完善用户信息'
					});
					if (res1[0]) throw res1[0];
					res1 = res1[1];
				} catch (err) {
					uni.hideLoading();
					return;
				}
				this.userProfile = res1;
			}
			this.p_phone.show = true;
		},
		// 手机号登录
		async loginBySms() {
			uni.showLoading({
				mask: true
			});
			let errors = [];
			errors = form.checkListData(this.l_list, true);
			if (errors.length) {
				const error = errors.find(i => i)[0];
				uni.hideLoading();
				this.$showToast(error);
				return;
			}
			errors = await form.checkListDataAsync(this.l_list, true);
			if (errors.length) {
				uni.hideLoading();
				const error = errors.find(i => i)[0];
				this.$showToast(error);
				return;
			}
			const listData = form.getListData(this.l_list);
			uni.hideLoading();
			this.login({
				phone: listData.phone,
				smsCode: listData.code
			});
		},
		// 统一的登录逻辑
		async login({ phone, smsCode, password }, code) {
			uni.showLoading({
				mask: true
			});
			let res1;
			try {
				res1 = await this.$api.user.get_user_wx_info({ jsCode: this.code });
			} catch (err) {
				this.getCode();
				uni.hideLoading();
				this.$showToast(err.message || '获取用户信息失败');
				return;
			}
			let res2;
			try {
				res2 = await this.$api.user.login({
					loginWay: 'WECHAT',
					loginMode: this.loginMode,
					wxUnionId: res1.result.unionid,
					password,
					phone,
					smsCode
				});
			} catch (err) {
				uni.hideLoading();
				this.$showToast(err.message || '登录失败');
				return;
			}
			let url;
			if (res2.result) {
				// 家校驿用户
				const jxyUserInfo = res2.result;
				const userProfile = this.userProfile;
				const wxUserId = res1.result;
				this.$store.commit('ALL_USERS_SUCCESS', { jxyUserInfo, userProfile, wxUserId });
				if (jxyUserInfo.relateStatus === 'noSchool' || !jxyUserInfo.teachSubject) {
					// 无学校/基本信息：
					url = '/packageA/pages/login/loginSuccess' + `?relateStatus=${jxyUserInfo.relateStatus}&phone=${phone}`;
				} else if (jxyUserInfo.relateStatus === 'noClass') {
					// 有学校/基本信息、无关联班级：
					url = '/packageA/pages/my/selectSquad?skip=1';
				} else {
					// 有学校/基本信息、有关联班级：
					url = '/pages/index/index';
				}
			} else {
				// 非家校驿用户
				url = '/packageA/pages/login/loginSuccess' + `?relateStatus=noSchool&phone=${phone}`;
			}
			await this.setTeacherPhoto();
			uni.hideLoading();
			this.$showToast('登录成功');
			try {
				this.updateJxyUserInfo(); // 设置头像后更新用户信息使具有头像
			} catch (err) {}
			uni.reLaunch({
				url
			});
		},
		// 设置用户头像作为老师头像
		async setTeacherPhoto() {
			let res1;
			try {
				res1 = await this.$api.common.download_file1(this.userProfile.userInfo.avatarUrl);
			} catch (err) {
				return;
			}
			const formData = {
				type: 'app/teacher/photo',
				nickName: this.userProfile.userInfo.nickName
			};
			const res2 = await this.$api.common.upload_files1({
				formData,
				filePath: res1.tempFilePath
			});
			const data = {
				nickName: this.userProfile.userInfo.nickName
			};
			if (res2.successCount) data.photo = res2.successData[0].absolutePath;
			let res3;
			try {
				res3 = await this.$api.user.set_teacher_info(data);
			} catch (err) {
				return;
			}
		},
		// 隐私协议
		async clickAgreement(type) {
			uni.showLoading({
				mask: true
			});
			let res1;
			try {
				res1 = await this.$api.agreement.get_agreement(type);
			} catch (err) {
				this.$showToast(err.message);
				return;
			}
			uni.setStorageSync('richTextData', {
				richTextData: res1.result,
				richTextTypeName: 'content'
			});
			uni.navigateTo({
				url: '/packageA/pages/richTextWeb/richText'
			});
			uni.hideLoading();
		}
	},
	onLoad(options) {
		if (options.loginType === loginEnum.loginType) {
			this.$store.commit('ALL_USERS_SUCCESS', { userProfile: {}, jxyUserInfo: {}, wxUserId: {} });
		}
		this.getCode();
	},
	onUnload() {
		if (this.codeTimer) clearInterval(this.codeTimer);
	},
	components: {
		MyCode
	}
};
</script>

<style lang="less" scoped>
@import '../../../common/css/font.css';
.page-background {
	position: fixed;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	z-index: -1;

	.background-image {
		height: 100%;
		position: relative;

		.image-top {
			width: 750rpx;
			height: 252rpx;
			position: absolute;
			top: 0;
		}

		.image-bottom {
			width: 750rpx;
			height: 340rpx;
			position: absolute;
			bottom: 0;
		}
	}
}

.page-navbar {
	.navbar-left {
		&.home {
			width: 46rpx;
			height: 47rpx;
		}
		&.back {
			width: 18rpx;
			height: 32rpx;
		}
	}
}

.login {
	padding: 0 71rpx;

	position: absolute;
	top: 20%;
}

.login-logo {
	margin-bottom: 50rpx;

	display: flex;
	flex-direction: column;
	align-items: center;

	.logo-icon {
		width: 140rpx;
		height: 140rpx;
		margin-bottom: 34rpx;
	}

	.logo-text {
		width: 100%;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.circle {
		width: 13rpx;
		height: 13rpx;
		border-radius: 50%;
		background-color: #545454;
		margin: 0 12rpx;
	}

	.font-type {
		font-family: 'fantizhenghei';
		font-size: 60rpx;
		color: #545454;
	}
}

.login-index {
	.index-rules {
		font-size: 24rpx;
		color: #707070;

		line-height: 40rpx;

		.hl {
			color: #ff6600;
		}
	}

	.index-buttons {
		margin-top: 40rpx;
	}
}

.login-form {
	.form-item {
		height: 136rpx;
		border-bottom: 2rpx solid #e3e4e6;

		position: relative;

		display: flex;
		align-items: center;

		.item-label {
			width: 190rpx;

			font-size: 28rpx;
			color: #a8a8a8;
		}

		.item-value {
			flex: 1;
			font-size: 28rpx;
			color: #222222;
		}

		.item-button {
			width: 156rpx;
			height: 48rpx;
			border: 2rpx solid #e3e4e6;
			border-radius: 20rpx;
			padding: 0 10rpx;

			position: relative;

			font-size: 24rpx;
			color: #a8a8a8;

			display: flex;
			justify-content: center;
			align-items: center;

			&.active {
				color: #ff6600;
				border: 2rpx solid #ff6600;
			}
		}

		.item-error {
			font-size: 28rpx;
			color: #ff0000;

			position: absolute;
			bottom: 10rpx;
			left: 190rpx;
		}
	}

	.form-buttons {
		margin-top: 40rpx;
	}
}

.login-button {
	height: 88rpx;
	border-radius: 44rpx;
	background-color: #eeeeee;
	margin-bottom: 20rpx;

	position: relative;

	font-size: 32rpx;
	color: #222222;

	display: flex;
	justify-content: center;
	align-items: center;

	&.primary {
		background-color: #ff6600;
		color: #ffffff;
	}
}

.popup1 {
	width: 594rpx;
	border-radius: 30rpx;
	background-color: #ffffff;
	overflow: hidden;
	text-align: center;
	color: #222222;

	.popup1-title {
		font-size: 36rpx;
		text-align: center;
		font-weight: 700;

		padding-top: 60rpx;
	}

	.popup1-content {
		line-height: 60rpx;
		padding: 40rpx 30rpx;

		font-size: 32rpx;
	}

	.popup1-buttons {
		height: 90rpx;
		border-top: 2rpx solid #e3e4e699;

		display: flex;

		.button-item {
			flex: 1;
			border-right: 2rpx solid #e3e4e699;
			background-color: #ffffff;

			position: relative;

			font-size: 32rpx;
			font-weight: 500;
			color: #222222;

			display: flex;
			align-items: center;
			justify-content: center;

			&:last-child {
				border-right: none;
			}

			&.primary {
				color: #ff6600;
			}
		}
	}
}
</style>
